import { createI18n } from 'vue-i18n';
import axios from 'axios';
import { LOCALSTORAGE_ENUM } from './enum/system';
import zh_CN from 'ant-design-vue/es/locale/zh_CN';
import en_US from 'ant-design-vue/es/locale/en_US';
import th_TH from 'ant-design-vue/es/locale/th_TH';
import localforage from 'localforage';
import { pageConfig } from './initial';

const host = import.meta.env.VITE_BASEURL;

export const langList = ref<LangItem[]>([]);

interface LangList {
  data: LangItem[];
  version: number;
}

interface LangItem {
  resource: string;
  value: string;
  key: string;
}

const http = axios.create();
const getLangList = async () => {
  const mapUrl = `${host}/profile/language/language.json`;
  const { data } = await http.get<LangList>(mapUrl);
  langList.value = data.data;
  return data;
};

let i18n: any;
/* 设置语言 */

export const initI18n = async () => {
  const setMessage = async (locale: string): Promise<string> => {
    const url = `${host}/profile/language/${locale}.json`;
    const { data } = await http.get(url);
    let messages: Record<string, any> = {};
    Object.keys(data).map(e => {
      messages = Object.assign(data[e], messages);
    });
    i18n.global.mergeLocaleMessage(locale, messages);
    return locale;
  };
  const locale: any = (await localforage.getItem(LOCALSTORAGE_ENUM.LANG)) || 'zh';
  i18n = createI18n({
    globalInjection: true,
    legacy: false,
    warnHtmlMessage: false,
    locale: locale,
    missingWarn: false,
    silentTranslationWarn: true,
  });
  await getLangList();
  const lang = await setMessage(locale);
  pageConfig.value.lang = languageMap[lang];
};

export const languageMap: Record<string, any> = {
  zh: zh_CN,
  en: en_US,
  th: th_TH,
};

export { i18n };
